package com.home.cca;

import static java.util.concurrent.CompletableFuture.runAsync;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.home.cca.adapters.GoodsAdapter;
import com.home.cca.adapters.OrderAdapter;
import com.home.cca.model.Goods;
import com.home.cca.model.Order;
import com.home.cca.network.ConfirmOrdersRequest;
import com.home.cca.network.PrintOrdersRequest;
import com.home.cca.network.QueryGoodsRequest;
import com.home.cca.network.QueryOrderDetailRequest;
import com.home.cca.network.QueryOrdersRequest;
import com.home.cca.network.SendOrdersRequest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@SuppressLint({"SetTextI18n", "MissingInflatedId", "NotifyDataSetChanged"})
public class MainActivity extends AppCompatActivity {

    private GoodsAdapter goodsAdapter;
    private OrderAdapter orderAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private Toast toast;
    private final List<Order> orders = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化商品列表
        RecyclerView goodsRecyclerView = findViewById(R.id.goodsRecyclerView);
        goodsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        goodsAdapter = new GoodsAdapter(this);
        goodsAdapter.setToast(this::toast);
        goodsRecyclerView.setAdapter(goodsAdapter);

        Button confirmOrdersButton = findViewById(R.id.confirmOrdersButton);
        Button sendOrdersButton = findViewById(R.id.sendOrdersButton);
        Button printOrdersButton = findViewById(R.id.printOrdersButton);

        confirmOrdersButton.setOnClickListener(v -> runAsync(this::confirmOrders));
        sendOrdersButton.setOnClickListener(v -> runAsync(this::sendOrders));
        printOrdersButton.setOnClickListener(v -> runAsync(this::printOrders));

        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        // 设置上拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener(() -> runAsync(() -> refreshOrder(null)));

        orderAdapter = new OrderAdapter(this, orders);
        orderAdapter.setIconConsumer(order -> runAsync(() -> showDialog(order)));
        orderAdapter.setNameConsumer(order -> runAsync(() -> refreshOrder(order)));
        orderAdapter.setDateConsumer(order -> runAsync(() -> printOrder(order)));

        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(orderAdapter);

        // 设置下拉加载更多的监听器
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if (!recyclerView.canScrollVertically(1)) {
                    // 当不能继续向下滚动时，即到达底部，加载更多数据
                    runAsync(() -> queryMoreOrders());
                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        runAsync(() -> refreshOrder(null));
    }

    private void refreshOrder(Order o) {
        try {
            List<Goods> goodsList = QueryGoodsRequest.query();
            if (goodsList == null || goodsList.isEmpty()) {
                toast("商品信息查询失败");
                return;
            }

            // 更新商品列表 UI
            runOnUiThread(() -> {
                goodsAdapter.setGoodsList(goodsList);
            });

            List<Order> orderList = QueryOrdersRequest.query(Objects.isNull(o) ? 0 : o.getSchoolId());
            runOnUiThread(() -> {
                orders.clear();
                orders.addAll(orderList);
                orderAdapter.notifyDataSetChanged();
                swipeRefreshLayout.setRefreshing(false);
            });

            for (Order order : orderList) {
                order.setMatList(QueryOrderDetailRequest.query(order.getId()));
                int index = orderList.indexOf(order);
                runOnUiThread(() -> orderAdapter.notifyItemChanged(index));
            }
        } catch (Exception e) {
            toast(e.getMessage());
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    private void queryMoreOrders() {
        try {
            // 调用接口获取初始价格和库存
            List<Order> orderList = QueryOrdersRequest.queryMore();
            if (orderList.isEmpty()) {
                toast("没有更多订单了");
                return;
            }
            runOnUiThread(() -> {
                orders.addAll(orderList);
                orderAdapter.notifyDataSetChanged();
            });
            for (Order order : orderList) {
                order.setMatList(QueryOrderDetailRequest.query(order.getId()));
                int index = orders.indexOf(order);
                runOnUiThread(() -> orderAdapter.notifyItemChanged(index));
            }
        } catch (Exception e) {
            toast(e.getMessage());
        }
    }

    private void confirmOrders() {
        try {
            List<Order> orders = filter("待确认");
            ConfirmOrdersRequest.confirm(orders);
            toast("订单确认成功");
            refreshOrder(null);
        } catch (IOException e) {
            toast(e.getMessage());
        }
    }

    private void sendOrders() {
        try {
            List<Order> orders = filter("待发货");
            SendOrdersRequest.send(orders);
            toast("订单发货成功");
            refreshOrder(null);
        } catch (IOException e) {
            toast(e.getMessage());
        }
    }

    private void printOrders() {
        try {
            List<Order> orders = filter("待收货");
            String buyDay = orders.get(0).getBuyDate().substring(0, 10);
            List<Order> os = orders.stream()
                    .filter(it -> it.getBuyDate().startsWith(buyDay))
                    .collect(Collectors.toList());
            String data = PrintOrdersRequest.print(os);
            runOnUiThread(() -> print(data));
        } catch (IOException e) {
            toast(e.getMessage());
        }
    }

    private void printOrder(Order order) {
        try {
            String data = PrintOrdersRequest.print(Collections.singletonList(order));
            runOnUiThread(() -> print(data));
        } catch (IOException e) {
            toast(e.getMessage());
        }
    }

    private void print(String data) {
        WebView webView = new WebView(this);
        // 获取 WebSettings 实例
        WebSettings webSettings = webView.getSettings();
        webSettings.setTextZoom(100);
        webSettings.setDomStorageEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        webView.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null);

        // 确保在页面加载完成后执行以下操作
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                PrintManager printManager = (PrintManager) getSystemService(PRINT_SERVICE);
                if (printManager != null) {
                    String jobName = "print";
                    PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(jobName);
                    printManager.print(jobName, printAdapter, new PrintAttributes.Builder().build());
                }
            }
        });
    }

    private void toast(String text) {
        runOnUiThread(() -> {
            // 如果当前有显示的 Toast，则取消它
            if (toast != null) {
                toast.cancel();
            }
            LayoutInflater inflater = getLayoutInflater();
            View layout = inflater.inflate(R.layout.custom_toast, findViewById(R.id.custom_toast_container));

            TextView textView = layout.findViewById(R.id.text);
            textView.setText(text);

            toast = new Toast(getApplicationContext());
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(layout);

            // 设置Toast的位置：Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL 表示居中对齐并靠底显示
            toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 100); // 第三个参数为偏移量，这里设置为0表示没有额外偏移

            toast.show();
        });
    }

    private List<Order> filter(String orderState) throws IOException {
        List<Order> os = orders.stream()
                .filter(it -> orderState.equals(it.getOrderState()))
                .collect(Collectors.toList());

        if (os.isEmpty()) {
            throw new IOException("无" + orderState + "的订单");
        }
        return os;
    }

    private void showDialog(Order order) {
        // 加载自定义布局文件
        LayoutInflater inflater = getLayoutInflater();
        View dialogLayout = inflater.inflate(R.layout.custom_dialog, null);

        // 获取对话框中的控件引用
        TextView tvDialogTitle = dialogLayout.findViewById(R.id.tvDialogTitle);
        TextView tvMonth = dialogLayout.findViewById(R.id.tvMonth);
        TextView tvCount = dialogLayout.findViewById(R.id.tvCount);
        TextView tvTotalMoneySum = dialogLayout.findViewById(R.id.tvTotalMoneySum);

        try {
            String month = order.getBuyDate().substring(0, 7);
            List<Order> orderList = QueryOrdersRequest.query(order.getSchoolId(), month).stream()
                    .filter(it -> Objects.equals(it.getOrderState(), "已收货"))
                    .collect(Collectors.toList());

            runOnUiThread(() -> {
                // 设置文本内容
                tvDialogTitle.setText(order.getSchoolName());
                tvMonth.setText(String.format("月份：%s", month));
                tvCount.setText(String.format("订单：%s 个", orderList.size()));
                tvTotalMoneySum.setText(String.format("金额：%s 元", orderList.stream().mapToDouble(Order::getTotalMoney).sum()));
                // 创建新的对话框
                new AlertDialog.Builder(this).setView(dialogLayout).show();
            });
        } catch (Exception e) {
            toast(e.getMessage());
        }
    }
}